﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;


namespace SYcwpb.Helpers
{
    public class WriteLog
    {
        //private static string LogPath = Application.StartupPath + "\\" + "Result.txt";
        private static object syncHelper = new object();
        private StreamWriter sw;
        private string LogPath = "";
        private bool IsOpening = false;

        public WriteLog(string logPath)
        {
            LogPath = Application.StartupPath + "\\" + logPath;
        }

        private bool Open()
        {
            if (IsOpening)
                return true;

            try
            {
                if (!File.Exists(LogPath))
                    sw = File.CreateText(LogPath);
                else
                {
                    FileStream fs = new FileStream(LogPath, FileMode.Truncate);
                    sw = new StreamWriter(fs);
                }
                IsOpening = true;
            }
            catch (System.Exception ex)
            {
                string err = ex.Message.ToString();
            }
            return IsOpening;
        }

        public void Write(string Info)
        {
            if (!IsOpening)
                if (!this.Open())
                    return;

            lock (syncHelper)
            {
                sw.Write(Info);
            }    
        }

        public void WriteLine(string Info)
        {
            if (!IsOpening)
                if (!this.Open())
                    return;

            lock (syncHelper)
            {
                sw.WriteLine(Info);
            }
        }

        public void Close()
        {
            if (sw != null)
            {
                sw.Flush();
                sw.Close();
                sw = null;

                IsOpening = false;
            }
        }
    }
}
